<template>
    <el-row>
        <el-form label-width='110px' :model='formItem' :rules="rules" ref="formItem">
            <el-row class="el-row-title">基本信息</el-row>
            <el-form-item label='商品名称' prop="name">
                <el-input v-model="formItem.name" :maxlength='20' placeholder="请输入商品名称,最多20字" clearable></el-input>
            </el-form-item>
            <!-- <el-form-item label='商品子名称'>
                <el-input v-model="formItem.subname" :maxlength='10' type='textarea' placeholder="请输入商品子名称"></el-input>
            </el-form-item> -->
            <el-form-item label='商品简介'>
                <el-input v-model="formItem.info" :rows="4" :maxlength='100' type='textarea' placeholder="请输入商品简介,最多100字"></el-input>
            </el-form-item>
            <el-form-item label='商品分组'>
                <el-select v-model="formItem.groups" multiple filterable allow-create default-first-option placeholder="请选择分组或输入新的分组" :filter-method="searchGroup" @change="groupChange">
                    <el-option v-for="(item,index) in groupData" :key="index" :label="item.name" :value="item.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label='单位'>
                <el-input v-model='formItem.unit' placeholder="请输入商品单位"></el-input>
            </el-form-item>
            <el-form-item label='商品图集' prop="img_url">
                <el-input v-model="formItem.img_url" style="display:none"></el-input>
                <draggable v-model="formItem.album">
                    <div class="upload-list" v-for="(item,index) in formItem.album" :key="index">
                        <img :src="item.img_url">
                        <div class="upload-list-cover">
                            <i class="el-icon-edit" @click="handleEdit(index)"></i>
                            <i class="el-icon-delete" @click="handleDel(index)"></i>
                        </div>
                    </div>
                </draggable>
                <div @click='uploadImg' class='upload-img'>
                    <i class='el-icon-upload'></i>
                </div>
                <el-row style="clear:both;color:#aaa">图片可拖动排序</el-row>
                <!-- <el-row style="clear:both">最佳尺寸：375*187px</el-row> -->
            </el-form-item>
            <el-form-item label='商品详情'>
                <el-row v-if='showEditor'>
                    <Ueditor :config="editorConfig" ueditorPath='/ueditor' :plugins="editorPlugins" :onChange="updateEditorContent" :uploadImage="uploadImage" :uploadAudio="uploadAudio" :uploadVideo="uploadVideo" :value="initContent" :progress="progress" />
                </el-row>
            </el-form-item>

            <el-row class="el-row-title">价格库存</el-row>
            <el-form-item label='商品规格'>
                <el-switch v-model="formItem.sku_status"></el-switch>
            </el-form-item>
            <el-form-item label='规格明细' v-if="formItem.sku_status">
                <!-- 高级规格 -->
                <div class="specification">
                    <ul class="spec-list" v-show="specification.length">
                        <li class="item" v-for="(item, index) in specification" :key="index">
                            <div class="name">
                                <el-select v-model="item.name" filterable allow-create default-first-option placeholder="请选择商品规格" @change="skuChange" style="float:left" size="small">
                                    <el-option v-for="(item,index) in skuSelections" :key="index" :label="item.name" :value="item.name">
                                    </el-option>
                                </el-select>
                                <i class="icon el-icon-circle-close" @click="delSpec(index)"></i>
                            </div>
                            <div class="values">
                                <span class="el-tag" v-for="(tag, num) in item.value" :key="num">
                                    <span class="el-select__tags-text">{{tag}}</span>
                                    <i class="el-tag__close el-icon-close" @click="delSpecTag(index, num)"></i>
                                </span>
                                <div class="add-attr">
                                    <el-select v-model="addValues[index]" filterable allow-create default-first-option placeholder="多个产品属性以空格隔开" size="small" @change="addSpecTag(index)" @visible-change="showSkuSub(item.name)">
                                        <el-option v-for="(sub,i) in skuSubSelections" :key="i" :label="sub.name" :value="sub.name">
                                        </el-option>
                                    </el-select>
                                </div>
                            </div>
                        </li>
                    </ul>
                    <div class="add-spec">
                        <el-button size="small" type="primary" plain :disabled="specification.length >= 5" @click="addSpec">添加规格项目</el-button>
                    </div>
                </div>

                <div class="example">
                    <table class="stock-table" v-show="formItem.sku_data.length">
                        <thead>
                            <tr>
                                <th v-for="(item,index) in specification" :key="index">{{item.name}}</th>
                                <th>价格</th>
                                <th>库存</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in formItem.sku_data" :key="index">
                                <td v-for="(n, specIndex) in specification.length" :key="specIndex" v-if="showTd(specIndex, index)" :rowspan="countSum(n)">
                                    {{getSpecAttr(specIndex, index)}}
                                </td>
                                <td>
                                    <el-input style="width:100px" v-model="item.price"></el-input>
                                </td>
                                <td>
                                    <el-input style="width:100px" v-model="item.store"></el-input>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

            </el-form-item>
            <el-form-item label='价格' required>
                <el-input-number v-model="formItem.price" :min="0" controls-position="right" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label='原价'>
                <el-input-number v-model="formItem.price_org" :min="0" controls-position="right" :precision="2"></el-input-number>
            </el-form-item>

            <el-row class="el-row-title">其他信息</el-row>
            <el-form-item label='快递邮费'>
                <el-radio-group v-model="formItem.fee_type" style="width:100%;margin:10px 0">
                    <el-row>
                        <el-col :span="8">
                            <el-radio :label="0">统一邮费</el-radio>
                            <br>
                            <el-input-number required v-model="formItem.fee_price" :min="0" controls-position="right" style="margin-top:10px" v-show="formItem.fee_type == 0"></el-input-number>
                        </el-col>
                        <el-col :span="8">
                            <el-radio :label="1">全国包邮</el-radio>
                        </el-col>
                    </el-row>
                </el-radio-group>
            </el-form-item>
            <el-form-item label='排序' prop="rank">
                <el-input-number v-model="formItem.rank" :min="0" controls-position="right"></el-input-number>
            </el-form-item>

            <el-form-item label='状态'>
                <el-switch v-model='formItem.status'></el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type='primary' @click="ok('formItem')" v-if="isClick">确定</el-button>
                <el-button type='primary' v-else>确定</el-button>
                <el-button @click='back'>返回</el-button>
            </el-form-item>
        </el-form>
        <Upload :show="showUpload" @on-selected="selectImg" @on-cancel="cancelUpload"></Upload>
    </el-row>
</template>

<script>
import draggable from "vuedraggable";
export default {
    layout: "shop",
    components: {
        draggable
    },
    data() {
        let checkPrice = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("请正确输入价格"));
            } else {
                callback();
            }
        };
        return {
            isClick: true,
            formItem: {
                id: 0,
                name: "",
                subname: "",
                info: "",
                detail: "",
                img_url: "",
                album: [],
                price: 0,
                price_org: 0,
                groups: "",
                rank: 0,
                sku_status: false,
                sku_data: [],
                unit: "",
                fee_type: 0, //0统一邮费1全国包邮
                fee_price: 0,
                status: true
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "change"
                    }
                ],
                price: [
                    {
                        required: true,
                        validator: checkPrice,
                        trigger: "blur"
                    }
                ],
                img_url: [
                    {
                        required: true,
                        message: "请上传商品图片",
                        trigger: "change"
                    }
                ]
            },
            groupData: [], //分组
            showUpload: false,
            progress: -1,
            initContent: "",
            showEditor: false,
            //规格
            skuSelections: [],
            skuSubSelections: [],
            specification: [],
            skuData: [],
            addValues: [] // 用来存储要添加的规格属性
        };
    },
    async asyncData({ app, query }) {
        let data = {};
        //分组
        const group = await app.$axios.$get(
            `/api/shop/home/shop/product/group/index`
        );
        if (group && group.errmsg === "ok") {
            data.groupData = group.data;
        }
        //规格
        const sku = await app.$axios.$get(`/api/shop/home/shop/sku/index`);
        if (sku && sku.errmsg === "ok") {
            data.skuSelections = sku.data;
        }

        if (query.id) {
            let config_data = await app.$axios.$get(
                `/api/shop/home/shop/product/product/info?id=${query.id}`
            );
            if (config_data && config_data.data) {
                data.formItem = config_data.data;
                data.initContent = data.formItem.detail;
                data.formItem.status = data.formItem.status ? true : false;
                data.formItem.sku_status = data.formItem.sku_status
                    ? true
                    : false;
                data.formItem.sku_data = data.formItem.sku;
                data.specification = data.formItem._skuData;
            }
            return data;
        } else {
            data.formItem = {
                id: 0,
                album: [],
                price: 0,
                price_org: 0,
                groups: [],
                rank: 0,
                sku_status: false,
                sku_data: [],
                fee_type: 0, //0统一邮费1全国包邮
                fee_price: 0,
                status: true
            };
            data.initContent = "";
            data.specification = [];
            return data;
        }
    },
    computed: {
        editorConfig() {
            return {
                zIndex: 1001
            };
        },
        editorPlugins() {
            return ["uploadImage", "insertCode", "uploadVideo", "uploadAudio"];
        }
    },
    mounted() {
        this.showEditor = true;
    },
    methods: {
        //分组
        async getGroup() {
            const group = await this.$axios.$get(
                `/api/shop/home/shop/product/group/index`
            );
            if (group && group.errmsg === "ok") {
                this.groupData = group.data;
            }
        },
        //选择分组
        async groupChange(val) {
            const res = await this.$axios.$post(
                `/api/shop/home/shop/product/group/add`,
                val
            );
            if (res && res.errmsg === "ok") {
                this.getGroup();
            }
        },
        //搜索分组
        async searchGroup(name) {
            if (name !== "") {
                const res = await this.$axios.$get(
                    `/api/shop/home/shop/product/group/index?name=${name}`
                );
                if (res && res.errmsg === "ok") {
                    this.groupData = res.data;
                }
            } else {
                this.getGroup();
            }
        },
        //添加分组
        async addGroup(name) {
            const res = await this.$axios.$post(
                `/api/shop/home/shop/product/group/add`,
                {
                    name: name
                }
            );
            if (res && res.errmsg === "ok") {
                this.getGroup();
            }
        },
        //上传图片
        uploadImg() {
            this.showUpload = true;
            this.editImg = false;
        },
        handleEdit(index) {
            this.showUpload = true;
            this.index = index;
            this.editImg = true;
        },
        selectImg(res) {
            this.showUpload = false;
            if (res.id > 0) {
                if (this.editImg) {
                    this.formItem.album[this.index].img_url = res.url;
                } else {
                    this.formItem.album.push({
                        img_url: res.url
                    });
                }
                this.formItem.img_url = this.formItem.album[0].img_url;
            }
        },
        cancelUpload() {
            this.showUpload = false;
        },
        handleDel(index) {
            this.formItem.album.splice(index, 1);
            if (!this.formItem.album.length) {
                this.formItem.img_url = "";
            }
        },
        //编辑器
        updateEditorContent(content) {
            this.formItem.detail = content;
        },
        uploadImage(e) {
            console.log(e.target);
            let file = e.target.files[0];
            let param = new FormData(); // 创建form对象
            param.append("file", file, file.name); // 通过append向form对象添加数据
            let config = {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            };
            return this.$axios.$post(
                "/api/app/home/file/add?type=1",
                param,
                config
            );
        },
        uploadAudio(e) {
            console.log(e.target);
        },
        uploadVideo(e) {
            console.log(e.target);
        },

        ok(formItem) {
            this.$refs[formItem].validate(valid => {
                if (valid) {
                    if (!this.formItem.sku_status && !this.formItem.price) {
                        return this.$message.warning("请正确输入价格");
                    }
                    if (this.formItem.sku_status) {
                        for (let key in this.formItem.sku_data) {
                            if (!this.formItem.sku_data[key].price) {
                                return this.$message.warning(
                                    "请填写商品规格价格"
                                );
                            }
                        }
                    }
                    this.isClick = false;
                    this.submit();
                } else {
                    this.$message.warning("请完善商品信息");
                    return false;
                }
            });
        },
        async submit() {
            let album = [];
            if (this.formItem.album) {
                for (let key in this.formItem.album) {
                    album.push(this.formItem.album[key].img_url);
                }
            }
            let data = {
                id: this.formItem.id,
                name: this.formItem.name,
                subname: this.formItem.subname,
                info: this.formItem.info,
                img_url: album[0],
                album: album,
                price: this.formItem.price,
                price_org: this.formItem.price_org,
                groups: this.formItem.groups,
                status: this.formItem.status,
                sku_status: this.formItem.sku_status,
                sku_data: this.formItem.sku_data,
                unit: this.formItem.unit,
                rank: this.formItem.rank,
                detail: this.formItem.detail,
                fee_type: this.formItem.fee_type,
                fee_price: this.formItem.fee_price
            };
            const res = await this.$axios.$post(
                "/api/shop/home/shop/product/product/add",
                data
            );
            if (res && res.errmsg === "ok") {
                this.$message.success({
                    type: "success",
                    message: "保存成功"
                });
                this.$router.push({
                    path: "/shop/product/product"
                });
            }
        },
        back() {
            this.$router.push({
                path: "/shop/product/product"
            });
        },
        //获取规格选项
        async getSku() {
            const sku = await this.$axios.$get(`/api/shop/home/shop/sku/index`);
            if (sku && sku.errmsg === "ok") {
                this.skuSelections = sku.data;
            }
        },
        //选择sku
        async skuChange(val) {
            if (val) {
                for (let key in this.specification) {
                    if (this.specification[key].name == val) {
                        this.specification[key].value = [];
                    }
                }
            }
            const sku = await this.$axios.$post(`/api/shop/home/shop/sku/add`, {
                skuData: this.specification
            });
            if (sku && sku.errmsg === "ok") {
                this.getSku();
            }

            const res = await this.$axios.$post(
                `/api/shop/home/shop/product/product/getSku`,
                {
                    skuData: this.specification
                }
            );
            if (res && res.errmsg === "ok") {
                this.formItem.sku_data = res.data;
            }
        },
        showSkuSub(name) {
            //规格下级选项展开
            for (let key in this.skuSelections) {
                if (this.skuSelections[key].name == name) {
                    this.skuSubSelections = this.skuSelections[key].sub;
                }
            }
        },
        // 添加规格项目
        addSpec() {
            if (this.specification.length < 3) {
                this.specification.push({
                    name: "",
                    value: []
                });
            }
        },
        // 删除规格项目
        delSpec(index) {
            this.specification.splice(index, 1);
            this.skuChange();
        },
        // 添加规格属性
        addSpecTag(index) {
            let arr = this.addValues[index].trim().split(" ");
            let newArr = this.specification[index].value.concat(arr);
            newArr = Array.from(new Set(newArr)); // 去重
            this.$set(this.specification[index], "value", newArr);
            this.clearAddValues(index);

            this.skuChange();
        },
        // 删除规格属性
        delSpecTag(index, num) {
            this.specification[index].value.splice(num, 1);
            this.skuChange();
        },
        // 清空 addValues
        clearAddValues(index) {
            this.$set(this.addValues, index, "");
        },
        /*
      根据传入的属性值，拿到相应规格的属性
      @params
        specIndex 规格项目在 advancedSpecification 中的序号
        index 所有属性在遍历时的序号
    */
        getSpecAttr(specIndex, index) {
            // 获取当前规格项目下的属性值
            const currentValues = this.specification[specIndex].value;
            let indexCopy;
            // 判断是否是最后一个规格项目
            if (
                this.specification[specIndex + 1] &&
                this.specification[specIndex + 1].value.length
            ) {
                indexCopy = index / this.countSum(specIndex + 1);
            } else {
                indexCopy = index;
            }
            const i = indexCopy % currentValues.length;
            if (i.toString() !== "NaN" && i % 1 === 0) {
                return currentValues[i];
            } else {
                return "";
            }
        },
        /*
      计算属性的乘积
      @params
        specIndex 规格项目在 advancedSpecification 中的序号
    */
        countSum(specIndex) {
            let num = 1;
            this.specification.forEach((item, index) => {
                if (index >= specIndex && item.value.length) {
                    num *= item.value.length;
                }
            });
            return num;
        },
        // 根据传入的条件，来判断是否显示该td
        showTd(specIndex, index) {
            // 如果当前项目下没有属性，则不显示
            if (!this.specification[specIndex]) {
                return false;
                // 自己悟一下吧
            } else if (index % this.countSum(specIndex + 1) === 0) {
                return true;
            } else {
                return false;
            }
        }
    }
};
</script>

<style scoped>
.el-row-title {
    background-color: #f8f8f8;
    font-size: 14px;
    font-weight: 700;
    padding: 10px;
    margin-bottom: 24px;
}

.example {
    margin-top: 20px;
}

.specification {
    display: inline-block;
    vertical-align: top;
    width: 480px;
}

.spec-list {
    background-color: #fff;
    border: 1px solid #d8d8d8;
    padding: 10px;
    list-style: none;
}

.item {
    margin-top: 5px;
}

.item:first-child {
    margin-top: 0;
}

.name {
    background: #f3f6fb;
    padding: 2px 8px;
    text-align: right;
    overflow: hidden;
}

.name .icon {
    display: none;
    color: #929292;
    cursor: pointer;
}

.name .icon:hover {
    color: #880000;
}

.name .el-input {
    float: left;
    width: 150px;
}

.name:hover .icon {
    display: inline-block;
}

.add-attr {
    display: inline-block;
    vertical-align: top;
    margin: 3px 0 0 8px;
}

.el-tag {
    margin: 8px 0 0 8px;
}

.add-spec {
    font-size: 13px;
    margin-top: 10px;
}

.stock-table {
    border: 1px solid #ddd;
}

.stock-table td,
th {
    padding: 5px 10px;
    border: 0;
    width: 100px;
    font-size: 14px;
    text-align: center;
}
</style><style>
#edui1,
#edui1_iframeholder {
    width: 100% !important;
}
</style>
